package com.mall.user.adapter.in.web.controller;

import com.mall.user.adapter.in.web.dto.CreateUserRequestDTO;
import com.mall.user.adapter.in.web.dto.UserListResponseDTO;
import com.mall.user.adapter.in.web.dto.UserResponseDTO;
import com.mall.user.domain.command.CreateUserCommand;
import com.mall.user.domain.model.User;
import com.mall.user.domain.port.in.CreateUserUseCase;
import com.mall.user.domain.port.in.GetUsersUseCase;
import com.mall.user.common.Result;
import com.mall.user.domain.model.Age;
import com.mall.user.domain.model.Email;
import com.mall.user.domain.model.UserName;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户控制器
 * 处理用户相关的HTTP请求
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户相关操作接口")
public class UserController {

    @Resource
    private CreateUserUseCase createUserUseCase;
    
    @Resource
    private GetUsersUseCase getUsersUseCase;

    @GetMapping
    @Operation(summary = "获取用户列表", description = "获取所有用户信息")
    public Result<UserListResponseDTO> getUsers(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "name", required = false) String namePattern) {
        
        log.info("获取用户列表请求: page={}, size={}, namePattern={}", page, size, namePattern);
        
        try {
            List<User> users=new ArrayList<>();
            long totalCount;
            
            // 根据查询条件获取用户列表
            if (namePattern != null && !namePattern.trim().isEmpty()) {
                // 按用户名模式查询
                users = getUsersUseCase.getUsersByNamePattern(namePattern.trim());
                totalCount = users.size(); // 模糊查询暂时不分页，直接返回所有匹配结果
            } else if (page != null && size != null && (page > 0 || size != 10)) {
                // 分页查询
                users = getUsersUseCase.getUsersWithPagination(page, size);
                totalCount = getUsersUseCase.getUserCount();
            } else {
                // 获取所有用户
                users = getUsersUseCase.getAllUsers();
                log.info("users:{}",users);
                totalCount = users.size();
            }
            
            // 转换为响应DTO
            List<UserResponseDTO> userResponseDTOs = users.stream()
                    .map(user -> UserResponseDTO.builder()
                            .id(user.getId())
                            .name(user.getName().name())
                            .age(user.getAge().age())
                            .email(user.getEmail().email())
                            .build())
                    .collect(Collectors.toList());
            
            // 构建响应
            UserListResponseDTO response;
            if (namePattern != null && !namePattern.trim().isEmpty()) {
                // 模糊查询结果
                response = UserListResponseDTO.of(userResponseDTOs);
            } else if (page != null && size != null && (page > 0 || size != 10)) {
                // 分页查询结果
                response = UserListResponseDTO.of(userResponseDTOs, totalCount, page, size);
            } else {
                // 全量查询结果
                response = UserListResponseDTO.of(userResponseDTOs);
            }
            
            log.info("用户列表查询成功: 返回{}个用户，总数{}", userResponseDTOs.size(), totalCount);
            return Result.success(response, "查询成功");
            
        } catch (IllegalArgumentException e) {
            log.warn("获取用户列表参数错误: {}", e.getMessage());
            return Result.fail(Result.HTTP_BAD_REQUEST, "USER10001", e.getMessage(), null);
        } catch (Exception e) {
            log.error("获取用户列表发生错误", e);
            return Result.fail(Result.HTTP_INTERNAL_ERROR, "USER10999", "获取用户列表失败，请稍后重试", null);
        }
    }

    @PostMapping
    @Operation(summary = "创建用户", description = "创建新用户")
    public Result<UserResponseDTO> createUser(@Valid @RequestBody CreateUserRequestDTO createUserRequestDTO){
        log.info("创建用户请求: {}", createUserRequestDTO);
        
        try {
            // 构建创建用户命令
            CreateUserCommand command = new CreateUserCommand(
                    UserName.of(createUserRequestDTO.getName()),
                    Age.of(createUserRequestDTO.getAge()),
                    Email.of(createUserRequestDTO.getEmail()));
            
            log.info("执行创建用户命令: {}", command);
            
            // 执行创建用户用例
            User createdUser = createUserUseCase.createUser(command);
            
            // 转换为响应DTO
            UserResponseDTO responseDTO = UserResponseDTO.builder()
                    .id(createdUser.getId())
                    .name(createdUser.getName().name())
                    .age(createdUser.getAge().age())
                    .email(createdUser.getEmail().email())
                    .build();
            
            log.info("用户创建成功: {}", responseDTO);
            return Result.success(responseDTO, "用户创建成功");
            
        } catch (com.mall.user.domain.exception.UserAlreadyExistsException e) {
            log.warn("用户已存在: {}", e.getUserName());
            return Result.fail(Result.HTTP_BAD_REQUEST, "USER00001", e.getMessage(), null);
        } catch (com.mall.user.domain.exception.UserCreationException e) {
            log.error("用户创建失败: {}", e.getMessage(), e);
            return Result.fail(Result.HTTP_INTERNAL_ERROR, "USER00002", e.getMessage(), null);
        } catch (IllegalArgumentException e) {
            log.warn("创建用户参数错误: {}", e.getMessage());
            return Result.fail(Result.HTTP_BAD_REQUEST, "USER00003", e.getMessage(), null);
        } catch (Exception e) {
            log.error("创建用户发生未知错误", e);
            return Result.fail(Result.HTTP_INTERNAL_ERROR, "USER00999", "系统错误，请稍后重试", null);
        }
    }
}
